Response : Web response

更新时间:
2024-05-15
下载文档

Response : Web response

The res object represents the HTTP response that an app sends when it gets an HTTP request.

In this documentation and by convention, the object is always referred to as res (and the HTTP request is req) but its actual name is determined by the parameters to the callback function in which you’re working.

For example:

app.get("/user/:id", function(req, res) {
  res.send("user " + req.params.id);
});

But you could just as well have:

app.get("/user/:id", function(request, response) {
  response.send("user " + request.params.id);
});

Support

The following shows WebResponse module APIs available for each permissions.

 User ModePrivilege Mode
res.app
res.write
res.end
res.send
res.sendFile
res.sendStatus
res.json
res.render
res.clearCookie
res.cookie
res.location
res.redirect
res.type
res.set
res.header
res.get

WebResponse object

WebResponse inherits from HttpServerResponse. For more properties, please refer to the HttpOutput module: HttpOutput.

res.app

  • app {Object} This WebApp object.

res.write(chunk)

  • chunk {String | Number | Boolean | Object | Buffer} Http body data.
  • Returns: {Boolean} true : success. false: fail.

This method inherit to HttpOutput. Send data to client. If 'Content-Length' not set, res.write() set 'Transfer-Encoding' to 'chunked', and this method can call multiple times. After write all data, user should call res.end() to end response.

res.end([chunk])

  • chunk {String | Number | Boolean | Object | Buffer} Http body data.

This method inherit to HttpOutput. If chunk is not empty, the chunk is sent to the client and the response is ended. After the response is finished, continuing to send data is invalid.

In general, it is recommended to use res.send() instead of res.end() to send data.

res.send(body)

  • body {String | Number | Boolean | Object | Buffer} HTTP response body.
  • Returns: {WebResponse} This WebResponse object: success. undefined: fail. Sends the HTTP response.

The body parameter can be a Buffer object, a String, an object, or an Array.

The res automatically sets the Content-Type header entry based on the chunk type. Content-Type is set as follows:

chunk typeContent-Type
StringREQUEST: text/plain; RESPONSE: text/html
Number, Boolean, Objectapplication/json
Bufferapplication/octet-stream

Example

res.send(Buffer.from("whoop"));
res.send({ some: "json" });
res.send("<p>some html</p>");

This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the Content-Length HTTP response header field (unless previously defined) .

When the parameter is a Buffer object, the method sets the Content-Type response header field to “application/octet-stream”, unless previously defined as shown below:

res.setHeader("Content-Type", "text/html");
res.send(Buffer.from("<p>some html</p>"));

When the parameter is a String, the method sets the Content-Type to "text/html":

res.send("<p>some html</p>");

When the parameter is an Object, app responds with the JSON representation:

res.send({ user: "tobi" });
res.send([1, 2, 3]);

res.sendFile(path[, options])

  • path {String} Send file path.
  • options {Object}
    • root {String} Root directory for relative filenames.
  • Returns: {Boolean} true : success. false: fail.

Transfer the file at the given path.

Example

The following example illustrates using res.sendFile to provide fine-grained support for serving files:

app.get("/user/:uid/photos/:file", function(req, res) {
  var uid = req.params.uid;
  var file = req.params.file;
  res.sendFile("/root/uploads/" + uid + "/" + file);
});

res.sendStatus(statusCode[,reason])

  • statusCode {Integer} HTTP response status code.
  • reason {String} Response info. default: status message.
  • Returns: {WebResponse} This WebResponse object: success. undefined: fail.

Sets the response HTTP status code to statusCode and send its string representation as the response body.

Example

res.sendStatus(200); // equivalent to res.status(200).send('OK')
res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')

If an unsupported status code is specified, the HTTP status is still set to statusCode and the string version of the code is sent as the response body.

res.sendStatus(9999); // equivalent to res.status(9999).send('9999')

res.json(obj[, status])

  • obj {Object} HTTP response body.
  • status {Integer} HTTP status code. default: 200.
  • Returns: {WebResponse} This WebResponse object: success. undefined: fail.

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

Example

res.json(null);
res.json({ user: "tobi" });
res.json({ user: "tobi" }, 200);
res.status(500).json({ error: "message" });

res.render(name[, options][, callback])

  • name {String} The file path of the view file to render.
  • options {Object} An object whose properties define local variables for the view.
    • cache {Boolean} Hinting to the engine it should cache. The variable cache is reserved for enabling view cache. Set it to true, if you want to cache view during development; view caching is enabled in production by default.
    • filename {String} File name of the view being rendered.
  • callback {Function} A callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response.
    • error {Error} Error object
    • html {String} Rendered string.

Renders a view and sends the rendered HTML string to the client.

The view argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the views setting , default to '/views'. If the path does not contain a file extension, then the view engine setting determines the file extension. If the path does contain a file extension, then app will load the module for the specified template engine (via require()) and render it using the loaded module’s WebApp function. The default template engine is `ejs'.

Example

// send the rendered view to the client
res.render("index");

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render("index", function(err, html) {
  res.send(html);
});

// pass a local variable to the view
res.render("user", { name: "Tobi" }, function(err, html) {
  // ...
});

res.cookie(name, value [, options])

  • name {String} Cookie name.
  • value {String | Object} Cookie value, a string or object converted to JSON.
  • options {Object}
    • maxAge {Integer} max-age in milliseconds, converted to expires.
    • path {String} default: "/".

Sets cookie name to value. The value parameter may be a string or object converted to JSON.

Example

res.cookie("name", "tobi", { path: "/admin" });
res.cookie("rememberme", "1", {
  expires: new Date(Date.now() + 900000),
  httpOnly: true,
});

res.clearCookie(name [, options])

  • name {String} Cookie name.
  • options {Object}

Clears the cookie specified by name. For details about the options object, see res.cookie().

Example

res.cookie("name", "tobi", { path: "/admin" });
res.clearCookie("name", { path: "/admin" });

res.location(path)

  • path {String} The response Location HTTP header to the specified path parameter.

A path value of “back” has a special meaning, it refers to the URL specified in the Referer header of the request. If the Refererheader was not specified, it refers to “/”.

After encoding the URL, if not encoded already, WebApp passes the specified URL to the browser in the Location header, without any validation.

Browsers take the responsibility of deriving the intended URL from the current URL or the referring URL, and the URL specified in the Location header; and redirect the user accordingly.

Example

res.location("/foo/bar");
res.location("http://example.com");
res.location("back");

res.redirect([status,] path)

  • status {Integer} HTTP status, default: 302.
  • path {String} Redirect URL path.
  • Returns: {Boolean} true : success. false: fail.

Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code.

Example

res.redirect("/foo/bar");
res.redirect("http://example.com");
res.redirect(301, "http://example.com");
res.redirect("../login");

Redirects can be a fully-qualified URL for redirecting to a different site:

res.redirect("http://google.com");

Redirects can be relative to the root of the host name. For example, if the application is on http://example.com/admin/post/new, the following would redirect to the URL http://example.com/admin:

res.redirect("/admin");

Redirects can be relative to the current URL. For example, from http://example.com/blog/admin/ (notice the trailing slash), the following would redirect to the URL http://example.com/blog/admin/post/new.

res.redirect("post/new");

Redirecting to post/new from http://example.com/blog/admin (no trailing slash), will redirect to http://example.com/blog/post/new.

If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.

Path-relative redirects are also possible. If you were on http://example.com/admin/post/new, the following would redirect to http://example.com/admin/post:

res.redirect("..");

A back redirection redirects the request back to the HTTP Referrer, defaulting to / when the Referrer is missing.

res.redirect("back");

res.type(type)

  • type {String} Type name.
  • Returns: {WebResponse} This.

Sets the Content-Type HTTP header to the MIME type as determined by the specified type. If type contains the “/” character, then it sets the Content-Type to the exact value of type, otherwise it is assumed to be a file extension and the MIME type.

Example

res.type(".html");
// => 'text/html'
res.type("html");
// => 'text/html'
res.type("json");
// => 'application/json'
res.type("application/json");
// => 'application/json'
res.type("png");
// => 'image/png'

res.set(field[, value])

  • field {String | Object} Header field or fields object.
  • value {String} Header field value.
  • Returns {WebResponse} this object.

Sets the response’s HTTP header field to value. To set multiple fields at once, pass an object as the parameter.

Example

res.set("Content-Type", "text/plain");

res.set({
  "Content-Type": "text/plain",
  "Content-Length": "123",
  ETag: "12345",
});

res.header(field[, value])

  • field {String | Object} Header field or fields object.
  • value {String} Header field value.
  • Returns {WebResponse} this object.

Aliased of res.set(field [, value]).

res.get(field)

  • field {String} Header field.
  • Returns: {String} Header field value.

Returns the HTTP response header specified by field. The match is case-insensitive.

Example

res.get("Content-Type");
// => "text/plain"

Events

end

A end event is emitted when the response had been done. The follow method will emitted 'end' event:

  • res.send()
  • res.sendFile()
  • res.sendStatus()
  • res.json()
  • res.end()

finish

The output stream finishs. The finish event is the same as the end event.

close

A close event is emitted when the response disconnected. Response may be closed normally or not properly, so the end or finish event may not be emitted before the close event.

error

A close event is emitted when the error occurs.

文档内容是否对您有所帮助?
有帮助
没帮助